package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.common.constant.Constants;
import cn.itsource.ymcc.common.constant.RConst;
import cn.itsource.ymcc.common.constant.RocketConstants;
import cn.itsource.ymcc.common.result.JsonResult;
import cn.itsource.ymcc.domain.Course;
import cn.itsource.ymcc.domain.CourseUserLearn;
import cn.itsource.ymcc.openfeign.OrderFeignClient;
import cn.itsource.ymcc.service.ICourseService;
import cn.itsource.ymcc.service.ICourseUserLearnService;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Component
@RocketMQMessageListener(consumerGroup = "course_user_learn_consumer",
        //Topic
        topic = RocketConstants.UPDATE_ORDER_STATUS_TOPIC,
        //TAGS
        selectorExpression = RocketConstants.UPDATE_ORDER_STATUS_TAG
)
public class CourseUserLearnConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private ICourseUserLearnService courseUserLearnService;
    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private ICourseService courseService;
    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            byte[] body = messageExt.getBody();
            String orderNo = new String(body, Constants.UTF8);
            JsonResult userIdAndCourseId = orderFeignClient.getUserIdAndCourseId(orderNo);
            JSONObject jsonObject = JSONObject.parseObject(userIdAndCourseId.getData().toString());
            Object o = jsonObject.get("userId");
            List<Integer> courseIds = (List<Integer>)jsonObject.get("courseId");
            for (Integer courseId : courseIds) {
                CourseUserLearn courseUserLearn = new CourseUserLearn();
                courseUserLearn.setCourseId(courseId.longValue());
                courseUserLearn.setLoginId(((Integer)o).longValue());
                Course course = courseService.getById(courseId);
                courseUserLearn.setStartTime(course.getStartTime());
                courseUserLearn.setEndTime(course.getEndTime());
                courseUserLearn.setState(RConst.Num.INT_0);
                courseUserLearn.setCourseOrderNo(orderNo);
                courseUserLearn.setCreateTime(new Date());
                courseUserLearnService.save(courseUserLearn);
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
